package com.zxl.thread;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 测试synchronized同步代码块中断退出
 */
public class SynchronizedExample {
    private final Object lock = new Object();

    public void synchronizedMethod() {
        synchronized (lock) {
            try {
                System.out.println(Thread.currentThread().getName() + " 进入同步块");
                // 模拟长时间操作
                Thread.sleep(5000);
                while (true){
                    System.out.println(Thread.currentThread().getName() + " 循环块");
                }
            } catch (InterruptedException e) {
                System.out.println(Thread.currentThread().getName() + " 被中断");
            }
        }
    }

    public static void main(String[] args) {
        SynchronizedExample example = new SynchronizedExample();
        Thread t = new Thread(example::synchronizedMethod);
        t.start();

//        try {
//            // 等待一段时间后尝试中断线程
//            Thread.sleep(1000);
            t.interrupt();
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
    }
}